import router, { resetRouter } from '@/router'
import { userLogin, getUserInfo } from '@/api/user'
import { clearSessionStorage, getSessionItem, setSessionItem } from '@/utils/token'
import { getUserID, setUserID, removeUserID } from '@/utils/storage'
import { removeTags, removeCacheViews } from '@/utils/tag'
import { ACCESS_TOKEN, MENU_TREE, USER_INFO } from '@/variables/storageVariables'
import { asyncRoutes } from '@/router/index.js'
const state = {
  userinfo: getSessionItem(USER_INFO) || {},
  token: getSessionItem(ACCESS_TOKEN) || {},
  menuTree: getSessionItem(MENU_TREE) || [],
  permissions: [],
  userID: null,
  userInfo: {},
  username: ''
}
const getters = {
  permissions: state => state.permissions,
  token: state => state.token,
  userInfo: state => state.userInfo,
  getters: state => state.permissions,
  username: state => state.username
}
const mutations = {
  setPermissions(state, permissions) {
    state.permissions = permissions
  },
  // 用户信息
  SET_USERINFO(state, userinfo) {
    state.userinfo = { ...userinfo }
    setSessionItem(USER_INFO, userinfo)
  },

  // 接口访问token key
  SET_ACCESS_TOKEN(state, token) {
    state.token = token
    setSessionItem(ACCESS_TOKEN, token)
  },

  // 接口访问token key
  SET_MENU_TREE(state, menuTree) {
    state.menuTree = menuTree
    setSessionItem(MENU_TREE, menuTree)
  },
  setUserID(state, userID) {
    state.userID = userID
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  setUsername(state, username) {
    state.username = username
  }
}

const actions = {
  setPermissions({ commit }, permissions) {
    commit('setPermissions', permissions)
  },
  // 用户登录
  login({ commit, dispatch }, data) {
    console.log(asyncRoutes, 'asyncRoutes111')
    return new Promise((resolve, reject) => {
      userLogin(data.username, data.password)
        .then(res => {
          console.log(res, 'login')
          console.log(data)
          if (res.success) {
            commit('setUserID', res.data.userID)
            setUserID(res.data.userID)
            const accessToken = res.data.access_token
            // commit('SET_USERINFO', res.data.userinfo)

            // const permissionList = ['superadmin', 'admin', 'user']
            // commit('setPermissions', [permissionList[res.data.permission]])
            // console.log([permissionList[res.data.permission]], 'permission')
            if (accessToken) {
              commit('SET_ACCESS_TOKEN', accessToken)
              dispatch('snackbar/sendSnackbar', { color: 'success', text: res.message, top: true }, { root: true })
              dispatch('getUserMenu', data) // 获取菜单
              resolve(res)
            } else {
              dispatch('snackbar/sendSnackbar', { color: 'error', text: `登录接口异常`, top: true }, { root: true })
              reject('fail')
            }
          } else {
            dispatch('snackbar/sendSnackbar', { color: 'error', text: `登录失败` + res.message }, { root: true })
            reject('fail')
          }
        })
        .catch(e => {
          return reject(e)
        })
    })
  },
  async getUserInfo({ commit, state, dispatch }) {
    // debugger;
    const id = getUserID()
    let res
    if (id) {
      res = await getUserInfo(state.userID ? state.userID : id)
    } else {
      // 未登录时 默认权限为3(unlogin) showName为空
      res = {
        data: {
          permission: 3,
          showName: ''
        }
      }
    }
    console.log(res, '用户info')
    commit('setUserInfo', res.data)
    commit('SET_USERINFO', res.data)
    const permissionList = ['superadmin', 'admin', 'user', 'outside'] // 对应 超管 集团级 公司级 项目级
    const data = {
      permissions: [permissionList[res.data.permission]],
      username: res.data.showName,
      'avatar|1': [
        'https://i.gtimg.cn/club/item/face/img/2/15922_100.gif',
        'https://i.gtimg.cn/club/item/face/img/8/15918_100.gif'
      ]
    }
    if (!res) {
      dispatch('snackbar/sendSnackbar', { color: 'error', text: '验证失败，请重新登录...', top: true }, { root: true })
      return false
    }
    const { permissions, username, avatar } = data
    if (permissions && username && Array.isArray(permissions)) {
      commit('setPermissions', permissions)
      commit('setUsername', username)
      return permissions
    } else {
      dispatch('snackbar/sendSnackbar', { color: 'error', text: '用户信息接口异常', top: true }, { root: true })
      window.location.reload()
      return false
    }
  },
  async getUserMenu({ commit, dispatch }, loginUserForm) {
    return new Promise((resolve, reject) => {
      commit('SET_MENU_TREE', asyncRoutes)
      resolve()
    })
  },

  // 退出
  async logout({ commit, dispatch }) {
    // return new Promise((resolve, reject) => {
    resetRouter()
    commit('SET_MENU_TREE', [])
    commit('SET_USERINFO', {})
    // commit('SET_ACCESS_TOKEN', {})
    await dispatch('resetAccessToken')
    clearSessionStorage()
    window.location.reload()
    router.push({ path: '/login' })
    // resolve()
    // })
  },
  resetAccessToken({ commit }) {
    commit('setPermissions', null)
    commit('SET_ACCESS_TOKEN', '')
    // removeAccessToken();
    clearSessionStorage(ACCESS_TOKEN)
    removeUserID()
    removeCacheViews()
    removeTags()
    // removeUserID();
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
